import React, { Fragment } from 'react'
import {
  StyleSheet,
  ScrollView,
  View,
  Text,
  InteractionManager,
  AppState,
  Alert
} from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import BasePage from 'src/pageP/base/base-page/index'
import OpenBtnSquare from './components/OpenBtnSquare'
import MemberTypeBtn from './components/MemberTypeBtn'
import OpenModal from './components/OpenModal'
import Gear from './components/Gear'
import { getMemberTypeList, memberPay, iosPayValidate, iapList } from 'src/utils/RequestAPI'
import { ScaleS, ScaleT, IS_IOS, IS_ANDROID } from 'src/utils/ScreenUtil'
import { isEmptyObjectFn, isString } from 'src/utils/JSTypeUtil'
import { LetterReg, NumberReg } from 'src/utils/RegUtil'
import { WXPay, IAPPay, IAPRestore, IAPProductsDetail } from 'src/utils/PayUtil'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { AgreementMember } from 'src/config/index'

import { connect } from 'react-redux'
import { UPDATE_USERINFO_ACTION } from '@store/actions/userinfo'
import { DO_REQUEST_MAIN_PAGE_B_ACTION } from 'src/pageB/main/main-page/store/action'
const defaultMembers = [
  {
    firstAudit: '无',
    id: 1,
    name: '非会员',
    operator: '1个',
    originalPrice: '0',
    postAddress: '1个',
    postPublishPrice: '60元/条',
    postRefreshPrice: '10元/条',
    postShow: '非会员区',
    postTop: '无',
    price: 0,
    publicTweet: '无',
    talentTalk: '免费3次',
    type: 0
  }
  // {
  //   firstAudit: '有',
  //   id: 5,
  //   name: '超级月度会员',
  //   operator: '6个',
  //   originalPrice: '299',
  //   postAddress: '6个',
  //   postPublishPrice: '30条/月',
  //   postRefreshPrice: '免费',
  //   postShow: '超级会员区',
  //   postTop: '有',
  //   price: 299,
  //   publicTweet: '有',
  //   talentTalk: '不限',
  //   type: 2
  // },
  // {
  //   firstAudit: '有',
  //   id: 6,
  //   name: '超级半年会员',
  //   operator: '12个',
  //   originalPrice: '1199',
  //   postAddress: '12个',
  //   postPublishPrice: '60条/月',
  //   postRefreshPrice: '免费',
  //   postShow: '超级会员区',
  //   postTop: '有',
  //   price: 1199,
  //   publicTweet: '有',
  //   talentTalk: '不限',
  //   type: 2
  // },
  // {
  //   firstAudit: '有',
  //   id: 7,
  //   name: '超级年度会员',
  //   operator: '不限',
  //   originalPrice: '1999',
  //   postAddress: '20个',
  //   postPublishPrice: '120条/月',
  //   postRefreshPrice: '免费',
  //   postShow: '超级会员区',
  //   postTop: '有',
  //   price: 1999,
  //   publicTweet: '有',
  //   talentTalk: '不限',
  //   type: 2
  // }
]
const memberSorts = [
  {
    key: 'price',
    value: '会员价格',
    unit: '元'
  },
  {
    key: 'postPublishPrice',
    value: '岗位发布'
  },
  {
    key: 'postRefreshPrice',
    value: ' 岗位刷新'
  },
  {
    key: 'postTop',
    value: '岗位置顶'
  },
  {
    key: 'postShow',
    value: '岗位展示'
  },
  {
    key: 'talentTalk',
    value: '人才沟通'
  },
  {
    key: 'operator',
    value: '招聘专员'
  },
  {
    key: 'postAddress',
    value: '工作地点'
  },
  {
    key: 'firstAudit',
    value: '优先审核'
  },
  {
    key: 'publicTweet',
    value: '公众号'
  }
]
const LinearGradientColors = {
  vip0: {
    btn: {
      start: { x: 0, y: 1 },
      end: { x: 1, y: 0 },
      colors: ['#A9A9A9', '#111111']
    },
    bg: '#F5F5F5',
    cellColor1: '#444444',
    cellColor2: '#A0A0A0'
  },
  vip1: {
    btn: {
      start: { x: 0, y: 0 },
      end: { x: 0, y: 1 },
      colors: ['#65D797', '#5DC9C5']
    },
    bg: '#E5F5EE',
    cellColor1: '#63D3A5',
    cellColor2: '#AEDFCA'
  },
  vip2: {
    btn: {
      start: { x: 0, y: 1 },
      end: { x: 1, y: 0 },
      colors: ['#EB427E', '#E942E3']
    },
    bg: '#FDECF0',
    cellColor1: '#E85C78',
    cellColor2: '#EFA9B7'
  }
}
const StringSplit = (reg, origin) => {
  const arr = origin.toString().split('')
  const resNotTested = arr.reduce((a, b) => (reg.test(b) ? a : a + b), '')
  const resTested = arr.reduce((a, b) => (reg.test(b) ? a + b : a), '')
  return {
    resTested,
    resNotTested
  }
}
// 发送行为
const mapDispatchToProps = dispatch => ({
  doRequestMainPage (payload) {
    const promise = DO_REQUEST_MAIN_PAGE_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})

@connect(
  ({ userinfo, BMineCenterStore }) => ({
    userinfo,
    ...BMineCenterStore
  }),
  mapDispatchToProps
)
class BMemberOpen extends BasePage {
  constructor (props) {
    super(props)
    const {
      navigation: {
        state: { params = {} }
      }
    } = this.props
    this.state = {
      header: {},
      leftDataSource: [],
      modalConfig: [],
      dataSource: [],
      ruleChecked: params.ruleChecked || false
    }
  }

  childRender () {
    const {
      leftDataSource,
      dataSource,
      modalConfig,
      ruleChecked
    } = this.state
    const hasData = modalConfig.length > 0
    return (
      <Fragment>
        <ScrollView
          style={styles.container}
          contentContainerStyle={styles.contentContainer}
        >
          <View style={styles.leftSlider}>
            <Gear
              style={[styles.gearWrap, IS_ANDROID && styles.gearWrapDone, hasData && styles.gearWrapDone]}
              useNativeDriver={IS_IOS}
              transition="translateX"
              duration={300}
              ref={this.setGearRef}
            />
            {leftDataSource.map(list => (
              <View style={styles.vipTypeWrap} key={list.id}>
                <MemberTypeBtn
                  style={{
                    ...styles.vipTypeBtn,
                    shadowColor: LinearGradientColors[`vip${list.type}`].bg
                  }}
                  linearProps={{
                    ...LinearGradientColors[`vip${list.type}`].btn
                  }}
                  nameZh={list.nameZh}
                  nameEn={list.nameEn}
                />
              </View>
            ))}
          </View>
          <ScrollView
            onLayout={this.onLayout}
            onContentSizeChange={this.onContentSizeChange}
            style={styles.rightScroll}
            scrollEventThrottle={16}
            onScroll={this.onScroll}
            horizontal={true}
            showsHorizontalScrollIndicator={false}
            alwaysBounceHorizontal={true}
          >
            {dataSource.map((list, index) => (
              <View key={`list${index}`}>
                <Text
                  style={[
                    styles.cellTitleText,
                    index === 0 && styles.cellTitleFirst
                  ]}
                >
                  {memberSorts[index].value}
                </Text>
                {list.map((item, indexx) => (
                  <View
                    key={`list${index}row${indexx}`}
                    style={styles.cellCommon}
                  >
                    {!!item.nameNum && (
                      <Text
                        style={[styles.nameNum, { color: item.cellColor1 }]}
                      >
                        {item.nameNum}
                      </Text>
                    )}
                    {!!item.nameZh && (
                      <Text style={[styles.nameZh, { color: item.cellColor2 }]}>
                        {item.nameZh}
                      </Text>
                    )}
                    {!!item.nameUnit && (
                      <Text
                        style={[styles.nameUnit, { color: item.cellColor1 }]}
                      >
                        {item.nameUnit}
                      </Text>
                    )}
                  </View>
                ))}
              </View>
            ))}
          </ScrollView>
        </ScrollView>
        <OpenBtnSquare
          style={[styles.bottomBtn, hasData && styles.bottomBtnDone]}
          useNativeDriver={IS_IOS}
          transition="translateY"
          duration={300}
          ruleChecked={ruleChecked}
          ruleCheck={this.ruleCheck}
          ruleClick={this.ruleClick}
          openClick={this.openClick}
        />
      </Fragment>
    )
  }

  componentDidMount () {
    ShowLoading()
    InteractionManager.runAfterInteractions(() => {
      let dataSource = []
      getMemberTypeList({})
        .then(res => {
          dataSource = res.data
          if (dataSource && !isEmptyObjectFn(dataSource)) {
            if (IS_IOS) {
              return iapList({})
            } else {
              return { data: [] }
            }
          }
        })
        .then(({ data: res = [] }) => {
          if (dataSource && !isEmptyObjectFn(dataSource)) {
            dataSource = dataSource.map(e => {
              const obj = res.find(f => f.iapId === e.openMemberIosPayId) || {}
              const price = obj.price
              return price ? { ...e, price } : e
            })
            dataSource = [
              defaultMembers[0],
              ...dataSource,
              ...defaultMembers.filter((e, i) => i > 0)
            ]

            const modalConfig = dataSource
              .filter(e => e.type === 1)
              .map(e => {
                const { resTested: nameEn, resNotTested: nameZh } = StringSplit(
                  LetterReg,
                  e.name
                )
                return {
                  ...e,
                  nameZh,
                  nameEn
                }
              })
            const leftDataSource = dataSource.map(e => {
              const { resTested: nameEn, resNotTested: nameZh } = StringSplit(
                LetterReg,
                e.name
              )
              return {
                id: e.id,
                type: e.type,
                nameZh,
                nameEn
              }
            })
            dataSource = memberSorts.map(f =>
              dataSource.map(e => {
                const {
                  resTested: nameNum,
                  resNotTested: nameZh
                } = StringSplit(NumberReg, e[f.key] + (f.unit || ''))
                return {
                  nameNum,
                  nameZh: nameNum ? nameZh : '',
                  nameUnit: nameNum ? '' : nameZh,
                  cellColor1: LinearGradientColors[`vip${e.type}`].cellColor1,
                  cellColor2: LinearGradientColors[`vip${e.type}`].cellColor2
                }
              })
            )
            this.setState({
              leftDataSource,
              dataSource,
              modalConfig
            })
          }
        })
        .finally(() => {
          DismissLoading()
        })
      AppState.addEventListener('change', this.handleAppStateChange)
    })
  }

  componentWillUnmount () {
    super.componentWillUnmount()
    AppState.removeEventListener('change', this.handleAppStateChange)
  }

  handleAppStateChange = appState => {
    console.log('handleAppStateChange')
    if (appState === 'active' && this.paying) {
      // todo test 应该查询订单
      ShowLoading()
      const { userinfo: { userId } } = this.props
      this.props.doRequestMainPage({ userId }).finally(() => {
        this.closeModal()
        DismissLoading()
        this.checkMemberStatus()
      })
      this.paying = false
    }
  }

  setGearRef = ref => {
    this.gearRef = ref
  }

  onLayout = e => {
    this.scrollViewViewWidth = Math.floor(e.nativeEvent.layout.width)
  }

  onContentSizeChange = width => {
    if (width === 0) {
      return
    }
    this.scrollViewAllWidth = Math.floor(width)
    const progress = this.scrollViewViewWidth / this.scrollViewAllWidth
    this.gearRef.setNativeProps({
      progress
    })
  }

  onScroll = ({
    nativeEvent: {
      contentOffset: { x }
    }
  }) => {
    x = Math.floor(x)
    const progress = Math.min(
      (x + this.scrollViewViewWidth) / this.scrollViewAllWidth,
      1
    )
    this.gearRef.setNativeProps({
      progress
    })
  }

  ruleCheck = () => {
    console.log('ruleCheck')
    if (this.state.ruleChecked) {
      this.openModal && this.openModal.close()
    }
    this.setState({
      ruleChecked: !this.state.ruleChecked
    })
  }

  ruleClick = () => {
    if (this.openModal) {
      this.openModal.close(() => {
        this.props.navigation.navigate('CommonWebView', {
          source: { uri: AgreementMember }
        })
      })
    } else {
      this.props.navigation.navigate('CommonWebView', {
        source: { uri: AgreementMember }
      })
    }
  }

  openClick = () => {
    console.log('openClick')
    const {

      modalConfig,
      ruleChecked
    } = this.state
    if (modalConfig.length === 0) {
      return
    }
    if (!this.state.ruleChecked) {
      CommonToast('请阅读并同意《人职初会员协议》')
      return
    }
    this.openModal = OpenModal({
      onCancel: this.onCancelModal,
      onConfirm: this.onConfirmModal,
      config: modalConfig,
      ruleChecked: ruleChecked,
      ruleCheck: this.ruleCheck,
      ruleClick: this.ruleClick
    })
  }

  onConfirmModal = index => {
    if (!this.state.ruleChecked) {
      CommonToast('请阅读并同意《人职初会员协议》')
      return
    }
    console.log('onConfirmModal', index)
    const { name: orderName, code } = this.state.modalConfig[index]
    const {
      userinfo: { userId },
      haveCompanyApply: { companyId }
    } = this.props
    const params = {
      businessType: 'openingMember',
      userId,
      companyId,
      code,
      orderName
    }
    if (IS_IOS) {
      Alert.alert(
        '开通会员',
        '',
        [{
          text: '去支付',
          style: '',
          onPress: () => {
            this.iapPayHandle(params)
          }
        }, {
          text: '恢复购买',
          style: '',
          onPress: () => {
            this.iapRestoreHandle()
          }
        }, {
          text: '取消',
          style: 'cancel'
        }]
      )
    } else {
      this.wxPayHandle(params)
    }
  }

  wxPayHandle = params => {
    ShowLoading()
    params['payWay'] = 'wxApp'
    memberPay({ params })
      .then(res => {
        this.paying = true
        return WXPay(res.data)
      })
      .then(res => {
        this.paying = false
        console.log('paying____success')
        const { userinfo: { userId } } = this.props
        return this.props.doRequestMainPage({ userId })
      })
      .then(res => {
        console.log('doRequestMainPage success')
        CommonToast('支付成功')
        this.closeModal()
      })
      .catch(error => {
        isString(error) && CommonToast(error)
      }).finally(() => {
        this.paying = false
        DismissLoading()
      })
  }

  iapRestoreHandle = () => {
    ShowLoading()
    const {
      userinfo: { userId },
      haveCompanyApply: { companyId }
    } = this.props
    let IAPRestoreRes = []
    IAPRestore().then((res = []) => {
      if (res.length === 0) {
        CommonToast('暂无可用购买记录，您可以拔打客服电话')
      } else {
        IAPRestoreRes = res
        this.paying = true
        const IAPProductIds = IAPRestoreRes.map(e => e.productId)
        return Promise.all(this.state.modalConfig.filter(e => IAPProductIds.includes(e.openMemberIosPayId)).map(({ name: orderName, code }) => {
          const params = {
            businessType: 'openingMember',
            userId,
            companyId,
            code,
            orderName,
            payWay: 'iosApp'
          }
          return memberPay({ params })
        }))
      }
    }).then((res = []) => {
      const {
        userinfo: { userId },
        haveCompanyApply: { companyId }
      } = this.props
      const newRes = IAPRestoreRes.map(e => {
        const finded = res.find(f => f.data.iapId === e.productId)
        if (finded) {
          return {
            ...e,
            ...finded
          }
        } else {
          return e
        }
      }).filter(e => e.recordId)
      return Promise.all(newRes.map(({ recordId, transactionReceipt: payload, transactionId }) => {
        const params = {
          payload,
          transactionId,
          recordId
        }
        const headers = { companyId, userId }
        return iosPayValidate({ params, headers })
      }))
    }).then((res = []) => {
      if (res.length > 0) {
        this.closeModal()
        const { userinfo: { userId } } = this.props
        return this.props.doRequestMainPage({ userId })
      } else {
        CommonToast('暂无可用购买记录，您可以拔打客服电话')
      }
    }).finally(() => {
      this.paying = false
      DismissLoading()
      this.checkMemberStatus()
    })
  }

  iapPayHandle = (params) => {
    ShowLoading()
    params['payWay'] = 'iosApp'
    memberPay({ params })
      .then(res => {
        this.paying = true
        const { iapId, recordId } = res.data
        const { companyId, userId } = params
        return IAPPay({ iapId, recordId, companyId, userId, businessType: 'OPENING_MEMBER' })
      })
      .then(res => {
        this.paying = false
        console.log('success')
        const { userinfo: { userId } } = this.props
        return this.props.doRequestMainPage({ userId })
      })
      .then(res => {
        console.log('doRequestMainPage success')
        CommonToast('支付成功')
        this.closeModal()
      })
      .catch(error => {
        isString(error) && CommonToast(error)
      }).finally(() => {
        DismissLoading()
        this.paying = false
        this.checkMemberStatus()
      })
  }

  checkMemberStatus = () => {
    const {
      member: { memberType }
    } = this.props
    if (memberType) {
      this.props.navigation.replace('BMemberDetail')
    }
  }

  closeModal = () => {
    this.openModal && this.openModal.close()
    this.checkMemberStatus()
  }
}

export default BMemberOpen

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
    marginBottom: ScaleS(60)
  },
  contentContainer: {
    flexDirection: 'row'
  },
  leftSlider: {
    width: ScaleS(100),
    flexDirection: 'column'
  },
  gearWrap: {
    marginLeft: ScaleS(8),
    marginVertical: ScaleS(14),
    transform: [{ translateX: -ScaleS(80) }]
    // backgroundColor: 'yellow'
  },
  gearWrapDone: {
    transform: [{ translateX: 0 }]
  },
  vipTypeWrap: {
    marginTop: ScaleS(15),
    height: ScaleS(52),
    justifyContent: 'center'
  },
  vipTypeBtn: {
    marginLeft: IS_IOS ? ScaleS(-5) : 0
  },
  rightScroll: {
    flex: 1
  },
  cellTitleText: {
    marginHorizontal: ScaleS(12),
    fontSize: ScaleT(15),
    lineHeight: ScaleS(35),
    fontWeight: 'normal'
  },
  cellTitleFirst: {
    marginLeft: 0
  },
  cellCommon: {
    marginTop: ScaleS(15),
    height: ScaleS(52),
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  },
  nameNum: {
    fontSize: ScaleT(18),
    fontWeight: 'bold'
  },
  nameZh: {
    fontSize: ScaleT(11),
    fontWeight: '400'
  },
  nameUnit: {
    fontSize: ScaleT(13),
    fontWeight: '400'
  },
  bottomBtn: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    transform: [{ translateY: ScaleS(60) }]
  },
  bottomBtnDone: {
    transform: [{ translateY: 0 }]
  }
})
